import { useAuthStore } from '../stores/auth' // 导入 useAuthStore
import { type UserInfo } from './interface'
import { login, loginWithRunworkToken } from '../utils/api'

class AuthMgr {
  private static instance: AuthMgr | null = null

  // 私有构造函数防止外部实例化
  private constructor() {
    console.log('AuthMgr instance created.')
  }

  // 静态方法用于获取单例实例
  public static getInstance(): AuthMgr {
    if (!AuthMgr.instance) {
      AuthMgr.instance = new AuthMgr()
    }
    return AuthMgr.instance
  }

  // 示例方法
  public setup(): void {
    console.log('Called setup.')
    const token = this.getTokenFormLoacal()
    const userInfo = this.getUserInfoFromLocal()
    this.updateLoginState(token, userInfo)
  }

  // 登录方法
  public async login(
    userName: string,
    password: string,
    codeKey: string,
    code: string
  ): Promise<any> {
    try {
      const data = await login(userName, password, codeKey, code)
      this.updateLoginState(data.token, data.userInfo)
      return data
    } catch (error) {
      return Promise.reject(error)
    }
  }

  public async ssoLogin(runworkToken: string, user?: any): Promise<any> {
    try {
      const data = await loginWithRunworkToken(user)
      // const userInfo: UserInfo = { username: user.user_id, name: user.name, userId: user.user_id }
      this.updateLoginState(data.token, data.userInfo)
      return data
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 登出方法
  public logout(): void {
    const { clearLoginState } = useAuthStore() // 创建 store 实例
    clearLoginState()
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')

    const routerBasePath = localStorage.getItem('routerBasePath')

    window.location.href = `${routerBasePath}login`
  }

  updateLoginState(token: string | null, userInfo: UserInfo | null) {
    const { setLoginState } = useAuthStore() // 创建 store 实例
    setLoginState(token ? token : '', userInfo ? userInfo : {})
    this.saveTokenToLocal(token)
    this.saveUserInfoToLocal(userInfo)
  }

  getTokenFormLoacal() {
    return localStorage.getItem('token')
  }

  saveTokenToLocal(token: string | null) {
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
  }

  getUserInfoFromLocal() {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      return JSON.parse(userInfoStr)
    } else {
      return {}
    }
  }

  saveUserInfoToLocal(userInfo: any) {
    localStorage.setItem('userInfo', JSON.stringify(userInfo ? userInfo : {}))
  }
}

export const authMgr = AuthMgr.getInstance()
export default authMgr
